package dymnd.ui;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import java.util.*;
import dymnd.plugin.*;

import java.awt.geom.*;
public class HSBColorChooser extends JPanel{
	
	
	public HSBColorChooser()	{
		
	}
	Image buffer;
	private Color selectedColor = Color.black;
	private Color secondaryColor = Color.white;
	
	//ArrayList<Swatch> swatches = new ArrayList<Swatch>();
	Color[] swatches;
	int rows = 200;
	int columns = 200;
	Robot robot;
	public HSBColorChooser(final PBus bus)	{
		
		//colors = new Color[rows*columns];
		
		swatches = createSwatches(rows, columns);
		setLayout(new GridLayout(rows, columns));
		//for(int i = 0; i < swatches.length; i++)	{
			//swatches[i].setSize(3, 3);
		try	{
			robot = new Robot();
		}	catch(Exception x)	{
			x.printStackTrace();
		}
			
		
		
		addMouseListener(new MouseAdapter()	{
				public void mousePressed(MouseEvent e)	{
					Rectangle r = new Rectangle(0, 0, getWidth(), getHeight());
					//selectedColor = s.getColor();
					if(r.contains(e.getX(), e.getY()));
						selectedColor = robot.getPixelColor(e.getXOnScreen(), e.getYOnScreen());
					bus.requestSetValue(PBus.KEY_PRIMARY_COLOR, selectedColor);
					//System.out.println(s.getColor());
				}
			});
			//add(swatches[i]);
		//}
		
		validate();
	}
	
	public void paintComponent(Graphics arg0)	{
		Graphics2D g = (Graphics2D)arg0;
		if(buffer == null || buffer.getWidth(this) != getWidth() || buffer.getHeight(this) != getHeight())	{
			buffer = createImage(getWidth(), getHeight());
		
			Dimension d = getSize();
			int index = 0;
			g.setColor(new Color(245, 240, 240));
			g.fillRect(0, 0, 10000, 10000);
			Graphics2D hsbG = (Graphics2D) buffer.getGraphics();
			for(double row = 0; row < rows; row++)	{
				for(double column = 0; column < columns; column++)	{
					hsbG.setColor(swatches[index]);
					hsbG.fill(new Rectangle2D.Double(((double)d.width/(double)columns)*column, ((double)d.height/(double)rows)*row, (double)d.width/(double)columns, (double)d.height/(double)rows));
					index++;
				}
			}
		}
		g.drawImage(buffer, 0, 0, this);
		
	}
	
	public Color getPrimaryColor()	{
		return selectedColor;
	}
	
	private Color[] createSwatches(int numRows, int numColumns)	{
		
				
		//for(int j = 0; j < rows; j++)	
		//ArrayList<Swatch> c = new ArrayList<Swatch>();
		Color[] c = new Color[numRows*numColumns];	
		int index = 0;
		for(int column = 0; column < numColumns; column++)	{
			double hue = 1.0/numColumns*column;
			for(int row = 0; row < numRows; row++)	{
				double sat = 1.0/numRows*row;
				c[index] = Color.getHSBColor((float)hue, (float)sat, 1);
				index++;
			}
		}
		/*
		for(int rows = 0; rows < numRows; rows++)	{
			c[index] = new Swatch(Color.getHSBColor(1, 1, 0.1f));
			index++;
		}
		*/
		
		
		
		
		return c;
	}
	
	
		
}
